﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin;
using Microsoft.Owin.Security;

namespace Sharp.Portal.Owin
{
    public class SharpSignInManager : SignInManager<SharpUser, int>
    {

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userManager"></param>
        /// <param name="authenticationManager"></param>
        public SharpSignInManager(UserManager<SharpUser, int> userManager, IAuthenticationManager authenticationManager)
            : base(userManager, authenticationManager)
        {
        }

        public static SharpSignInManager Create(IdentityFactoryOptions<SharpSignInManager> options, IOwinContext context)
        {
            return new SharpSignInManager(context.GetUserManager<SharpUserManager>(), context.Authentication);
        }

        /// <summary>
        /// 根据用户名密码，验证用户登录
        /// </summary>
        /// <param name="userName"></param>
        /// <param name="password"></param>
        /// <param name="isPersistent"></param>
        /// <param name="shouldLockout"></param>
        /// <returns></returns>
        public override async Task<SignInStatus> PasswordSignInAsync(string userName, string password, bool isPersistent,
            bool shouldLockout)
        {
            var x = await base.PasswordSignInAsync(userName, password, isPersistent,
                shouldLockout);

            return x;
        }
        public override async Task SignInAsync(SharpUser user, bool isPersistent, bool rememberBrowser)
        {
            var userIdentity = await CreateUserIdentityAsync(user);
            // Clear any partial cookies from external or two factor partial sign ins
            AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie, DefaultAuthenticationTypes.TwoFactorCookie);
            if (rememberBrowser)
            {
                var rememberBrowserIdentity = AuthenticationManager.CreateTwoFactorRememberBrowserIdentity(ConvertIdToString(user.Id));
                AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity, rememberBrowserIdentity);
            }
            else
            {
                //AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = isPersistent }, userIdentity);
                if (isPersistent)
                {
                    AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true }, userIdentity);
                }
                else
                {
                    AuthenticationManager.SignIn(new AuthenticationProperties { IsPersistent = true, ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(30) }, userIdentity);
                }
            }
        }
    }
}